package org.todo.controller;

import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import java.security.Principal;

import javax.portlet.PortletRequest;

/**
 * Utility class used by controllers
 * @author Matthias Braunhofer
 */
public class ControllerUtil {

    /**
     * Returns the userid of the currently logged in user or null if the user is
     * currently not logged in
     * @param request
     * @return
     */
    public static String getUserName(PortletRequest request) {
        Principal userPrincipal = request.getUserPrincipal();
        return (userPrincipal == null) ? null : userPrincipal.getName();
    }

    /**
     * Returns the screen name from a given user id
     * @param username
     * @return
     */
    public static String getUserScreenName(String username) {
        User user = null;
        try {
            user = UserLocalServiceUtil.getUser(Long.parseLong(username));
        } catch (Exception e) {
            //ignore excptions
        }
        return (user == null) ? null : user.getScreenName();
    }

    /**
     * Returns the id of a user-selected category from the session state or -1 if none
     * has been stored
     * @param request
     * @return
     */
    public static int getSelectedCategoryFromSession(PortletRequest request) {
        Object selectedCategory = request.getPortletSession().getAttribute("selectedCategory");
        return selectedCategory != null ? Integer.valueOf(selectedCategory.toString()) : -1;
    }
}
